package com.yklx.youke.admin.service.impl;

import com.yklx.youke.admin.mapper.PermissionMapper;
import com.yklx.youke.admin.service.PermissionService;
import com.yklx.youke.entity.Permission;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {

    private final PermissionMapper permissionMapper;

    public PermissionServiceImpl(PermissionMapper permissionMapper) {
        this.permissionMapper = permissionMapper;
    }

    @Override
    public List<Permission> getUserPermissions(String userId) {
        return permissionMapper.getUserPermissions(userId);
    }

    @Override
    public List<Permission> getAllPermissions() {
        return permissionMapper.getAllPermissions();
    }

    @Override
    public Permission getPermissionById(String permissionId) {
        return permissionMapper.getPermissionById(permissionId);
    }

    @Override
    public boolean createPermission(Permission permission) {
        return permissionMapper.insertPermission(permission) > 0;
    }

    @Override
    public boolean updatePermission(Permission permission) {
        return permissionMapper.updatePermission(permission) > 0;
    }

    @Override
    public boolean deletePermission(String permissionId) {
        return permissionMapper.deletePermission(permissionId) > 0;
    }

    @Override
    public boolean hasPermission(String userId, String permissionCode) {
        Permission permission = permissionMapper.getPermissionByCode(permissionCode);
        if (permission == null) {
            return false; // 权限代码不存在
        }

        // 检查用户是否拥有该权限
        List<Permission> userPermissions = permissionMapper.getUserPermissions(userId);
        return userPermissions.stream()
                .anyMatch(p -> p.getPermissionCode().equals(permissionCode));
    }
}